<?php

// +----------------------------------------------------------------------
// | SinianAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 祀念网络科技有限公司 [ http://www.sinianwork.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：
// | github 代码仓库：
// +----------------------------------------------------------------------

namespace app\api\controller;
use app\data\model\ControlClaimListModel;
use app\data\model\ControlClaimModel;
use app\data\model\StorehouseDataModel;
use app\data\model\EnterStorehouseItemModel;
use think\facade\Db;
use think\admin\extend\CodeExtend;
use think\admin\Controller;

/**
 * 计划领用接口
 * Class Plan
 * @package app\index\controller
 */
class Plan extends Controller
{
    /**
     * 获取领用列表
     */
    public function getPlanCollect(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {$this->error('请先登陆');}
        if(!isset($data['authorize']) || !$data['authorize']) {$this->error('请先登陆');}
        //搜索
        if(isset($data['plan_title']) && $data['plan_title']){
            $str = substr( $data['plan_title'], 0, 1 );
            if($str == 'L'){
                $where[]=['id','like',$data['plan_title'].'%'];
            }else{
                $where[]=['plan_title','like','%'.$data['plan_title'].'%'];
            }
        }else{
            $where = [];
        }
        $where[] = ['deleted','eq',0];
        if($data['admin_id'] == 10000){
            $where = array();
        }elseif($data['authorize'] == 7){
            //保管员-物资供应中心
            $where = array();
        }else{
            $where = array('admin_id'=>$data['admin_id']);
        }
        $planList = ControlClaimModel::where($where)->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        $this->success('ok',$planList,1);
    }

    /**
     * 获取领用详情
     */
    public function getPlanCollectDetail(){
        $data = input('post.');
        if(!$data['plan_id']) {$this->error('数据不存在');}
        $where = array(
            'id'=>$data['plan_id']
        );
        $planList = ControlClaimModel::where($where)->find();
        $planList['plan_list'] = ControlClaimListModel::where('plan_id',$data['plan_id'])->select()->toArray();
        $this->success('ok',$planList,1);

    }


    /**
     * 获取领用查看流程
     */
    public function getPlanCollectLc(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['plan_id']) {$this->error('数据不存在');}
        $where = array(
            'collect_id'=>$data['plan_id']
        );
        $plan_list = Db::name('sn_control_claim_time')->where($where)->orderRaw("field(admin_authorize,'8','2','4')")->select();
        $this->success('ok',$plan_list,1);

    }

    /**
     * 获取添加审核页面
     */
    public function getPlanCollectAdd(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $where['is_deleted'] = 0;
        // $list['wuliu_list'] = Db::name('system_user')->where('authorize','8')->where($where)->field('id,username,nickname')->select()->toArray();
        $list['keshi_list'] = Db::name('system_user')->where('authorize','2')->where($where)->field('id,nickname,username')->select()->toArray();
        $list['jingyi_list'] = Db::name('system_user')->where('authorize','4')->where($where)->field('id,nickname,username')->select()->toArray();
        $this->success('ok',$list,1);

    }


    /**
     * 获取库存列表
     */
    public function getIntegration()
    {
        $input = input('post.');
        if(!$input['admin_id']){$this->error('请先登陆');}
        //判断库存表是否存在
        $isTable = Db::query('SHOW TABLES LIKE '."'".'sn_enter_storehouse_'.$input['admin_id']."'");
        if(!$isTable){$this->error('暂无可领取物资');}
        //搜索
        $so_where[]=['material_code','like',$input['material_code'].'%'];
        $so_where[]=['material_name','like','%'.$input['material_name'].'%'];
        $ksList = Db::name('sn_enter_storehouse_'.$input['admin_id'])->where($so_where)->limit(($input['page']-1)*$input['size'], $input['size'])->column('material_num','material_code');
        if(empty($ksList)){$this->success('暂无可领取物资',[],1);}
        $data = Db::name('sn_enter_storehouse_item')->whereIn('material_code',array_keys($ksList))->field('*,sum(material_num) as material_num')->select()->toArray();
        $material_codes = array_column($data,'material_code');
        $order = 'field(material_code,'.implode(',',$material_codes).')';
        $material_nums = array_column($data,'material_num');
        //判断库存表是否存在
        $isTable = Db::query('SHOW TABLES LIKE '."'".'sn_enter_storehouse_'.$input['admin_id']."'");
        if($isTable){
            $data = Db::name('sn_enter_storehouse_'.$input['admin_id'])->whereIn('material_code',$material_codes)->order(Db::raw($order))->select()->toArray();
                foreach ($data as $k=>$v){
                    $data[$k]['material_xjptice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
                    $data[$k]['storehouse_num'] = $material_nums[$k];
                }
                $newData = array();
                foreach ($data as $k=>$v){
                    $newData[$v['material_code']] = $v;
                }
                //获取出库数据
                $ControlClaimListModel = new ControlClaimListModel();
                $claim_nums = $ControlClaimListModel->whereIn('status',[0,1])->whereIn('material_code',array_keys($newData))->group('material_code')->column('sum(material_num)','material_code');
                foreach ($newData as $ks=>$vs){
                    if(!isset($claim_nums[$ks])){
                        $newData[$ks]['claim_num'] = 0;
                        $newData[$ks]['surplus_num'] = $newData[$ks]['storehouse_num'];
                    }else{
                        $newData[$ks]['claim_num'] = $claim_nums[$ks];
                        $newData[$ks]['surplus_num'] =  sprintf("%01.2f", $newData[$ks]['storehouse_num'] - $claim_nums[$ks]);
                    }
                }
                sort($newData);
                $data = $newData;
        }else{
            $data = array();
        }
        $this->success('ok',$data,1);
    }

    /**
     * 添加审核
     */
    public function addPlanCollect(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        // if(!isset($data['duizu_id']) || empty($data['duizu_id'])){$this->error('请选择审核队干');}
        // if(!isset($data['keshi_id']) || empty($data['keshi_id'])){$this->error('请选择审核科室科长');}
        // if(!isset($data['gykz_id']) || empty($data['gykz_id'])){$this->error('请选择供应科长');}
        if(!isset($data['plan_list']) || empty($data['plan_list'])){$this->error('材料列表不可为空');}
        $plan_list = json_decode($data['plan_list'],true);
        foreach ($plan_list as $ks => $vs){
            if(!$vs['material_num'] || empty($vs['material_num'])){$this->error($vs['material_name'].'('.$vs['material_code'].')'.'数量不可为0');}
        }
        $userInfo = Db::name('system_user')->where('id',$data['admin_id'])->where('is_deleted',0)->field('id,nickname,username')->find();
        if(!isset($data['id']) || !$data['id']){
            // 生成计划ID
            $data['id'] = CodeExtend::uniqidNumber(10,'L');
            $is_status = true;
        }else{
            $is_status = false;
        }
        //获取标题
        $data['plan_data_status'] = date('Ym',time());
        $data['plan_title'] = date('Y年m月d日',time()).'领用单';
        $data['admin_id'] = $userInfo['id'];
        $data['admin_name'] = $userInfo['username'];
        $data['status'] = 0;
        //查询审核人信息
        $auth_auditing = [$data['keshi_id'],$data['jingyi_id']];
        $userList = Db::name('system_user')->where(['is_deleted'=>0,'status'=>1])->whereIn('id',$auth_auditing)->field('id,username,authorize')->orderRaw("field(authorize,'2','4')")->select()->toArray();
        //开启事务
        Db::startTrans();
        try{
            //删除计划流程数据
            $time_del = Db::name('sn_control_claim_time')->where('collect_id',$data['id'])->delete();
            if ($time_del === false) {throw new \Exception("服务器错误");}
            // 添加计划表流程数据
            $shenen = array();
            // if(count($userList) == 0){
            //     $shenen[0]['collect_id'] = $data['id'];
            //     $shenen[0]['admin_id'] = 0;
            //     $shenen[0]['admin_name'] = '物流配送中心';
            //     $shenen[0]['admin_authorize'] = 8;
            // }else{
            //     foreach ($userList as $ks=>$vs){
            //         $shenen[$vs['authorize']]['collect_id'] = $data['id'];
            //         $shenen[$vs['authorize']]['admin_id'] = $vs['id'];
            //         $shenen[$vs['authorize']]['admin_name'] = $vs['username'];
            //         $shenen[$vs['authorize']]['admin_authorize'] = $vs['authorize'];
            //     }
            //     $auth_status = in_array(4,array_column($shenen,'admin_authorize'));
            //     if(!$auth_status){
            //         $shenen[4] = array('collect_id'=>$data['id'],'admin_id'=>0,'admin_name'=>'精益化管理部','admin_nickname'=>'精益化管理部','admin_authorize'=>4);
            //     }
            // }
//                dump($shenen);die;
            $inserAdd = [];
            foreach ($userList as $ks=>$vs){
                $shenen[$vs['authorize']]['collect_id'] = $data['id'];
                $shenen[$vs['authorize']]['admin_id'] = $vs['id'];
                $shenen[$vs['authorize']]['admin_name'] = $vs['username'];
                $shenen[$vs['authorize']]['admin_authorize'] = $vs['authorize'];
                $inserAdd[] = $shenen[$vs['authorize']];
            }
            // dump($inserAdd);die;
            // $column = array_column($shenen,'admin_authorize');
            // array_multisort($column,SORT_ASC,$shenen);
            //首次审批权限
            $data['plan_status'] = $inserAdd[0]['admin_authorize'];
            $applyId = Db::name('sn_control_claim_time')->insertAll($inserAdd);
            // 判断是否添加成功
            if (!$applyId) {throw new \Exception("服务器错误");}
            //删除计划子表数据
            $listDel = Db::name('sn_control_claim_list')->where('plan_id',$data['id'])->delete();
            if ($listDel === false) {throw new \Exception("服务器错误");}
            $StirehouseData = new StorehouseDataModel();
            //获取剩余物资
            $adminStorehouse = Db::name('sn_enter_storehouse_'.$data['admin_id'])->column('material_num','material_code');
            //数组合并array_combine($k,$v)  return $k=>$v
            $combineData = array_combine(array_column($plan_list,'material_code'),array_column($plan_list,'material_num'));
            foreach ($combineData as $key=>$val){
                $he = $adminStorehouse[$key] - $val;
                if($he < 0 ){throw new \Exception($key.'数量不足');}
                // 减自己库存
                $res = Db::name('sn_enter_storehouse_'.$data['admin_id'])->where('material_code',$key)->dec('material_num',$val)->update();
                if (!$res) {throw new \Exception("服务器错误");}
            }
            $cate_list = array();
            //组合数组
            foreach ($plan_list as $k=>$v){
                $cate_list[$k]['material_code'] = $v['material_code'];
                $cate_list[$k]['material_name'] = $v['material_name'];
                $cate_list[$k]['material_model'] = $v['material_model'];
                $cate_list[$k]['material_unit'] = $v['material_unit'];
                $cate_list[$k]['material_price'] = $v['material_price'];
                $cate_list[$k]['material_num'] = $v['material_num'];
                $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_num'] * $v['material_price'][$k]);
                $cate_list[$k]['plan_id'] = $data['id'];
                $cate_list[$k]['plan_time'] = date('Y-m-d H:i:s',time());
                // $cate_list[$k]['cate_id'] = $v['cate_id'];
                $cate_list[$k]['admin_id'] = $userInfo['id'];
                $cate_list[$k]['admin_name'] = $userInfo['username'];
                $cate_list[$k]['status'] = 1;
            }
            // 子表数据添加
            $applyAll = Db::name('sn_control_claim_list')->insertAll($cate_list);
            if (!$applyAll) {throw new \Exception("服务器错误");}
            $data['plan_list'] = json_encode($cate_list,true);
            unset($data['plan_list']);
            //主表数据添加
            if($is_status){
                $planSave = ControlClaimModel::insertGetId($data);
            }else{
                $planSave = ControlClaimModel::where('id',$data['id'])->update($data);
            }
            if (!$planSave) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }



    /**
     * 获取领用审批列表
     */
    public function getClanmList(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {$this->error('请先登陆');}
        //搜索
        if(isset($data['plan_title']) && $data['plan_title']){
            $str = substr( $data['plan_title'], 0, 1 );
            if($str == 'L'){
                $where[]=['id','like',$data['plan_title'].'%'];
            }else{
                $where[]=['plan_title','like','%'.$data['plan_title'].'%'];
            }
        }else{
            $where = [];
        }
        //权限重构
        $where[] = array( 'deleted','=', 0);
        // if($data['authorize'] == 8){
        //     //物流配送中心
        //     $where[] = array('wuliu_id','=',$data['admin_id']);
        //     $planList = ControlClaimModel::where($where)->whereIn('plan_status','8,2,4')->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        // }else
        if($data['authorize'] == 2){
            //科室
            $where[] = array('keshi_id','=',$data['admin_id']);
            $planList = ControlClaimModel::where($where)->whereIn('plan_status','2,4')->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }elseif($data['authorize'] == 4){
            //精益化管理部
            $where[] = array('plan_status','=',4);
            $planList = ControlClaimModel::where($where)->whereIn('status',[0,1])->whereIn('jingyi_id',[$data['admin_id'],0])->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }elseif($data['admin_id'] == 10000){
            $where = [];
        }
        $this->success('ok',$planList,1);

    }


    /**
     * 审核通过
     */
    public function planCollectResume(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['plan_id']){$this->error('计划不存在');}
        if(!$data['authorize']){$this->error('权限错误');}
        //开启事务
        Db::startTrans();
        try{
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            // if($data['authorize'] == 8){
            //     $applyList = Db::name('sn_control_claim_time')->where(['collect_id'=>$data['plan_id'],'admin_id'=>$data['admin_id']])->update($planTime);
            //     $planInfo['plan_status'] = 2;
            // }else
            if ($data['authorize'] == 2){
                $applyList = Db::name('sn_control_claim_time')->where(['collect_id'=>$data['plan_id'],'admin_id'=>$data['admin_id']])->update($planTime);
                $planInfo['plan_status'] = 4;
            }elseif ($data['authorize'] == 4){
                $planInfo['status'] = 1;
                $applyPlan = Db::name('sn_control_claim_list')->where(['plan_id'=>$data['plan_id']])->update(['status'=>1]);
                if (!is_int($applyPlan)) {throw new \Exception("服务器错误");}
                // 子表数据修改
                $applyList = Db::name('sn_control_claim_time')->where(['collect_id'=>$data['plan_id'],'admin_authorize'=>4])->update($planTime);
            }
            if (!is_int($applyList)) {throw new \Exception("服务器错误");}
            $resut = ControlClaimModel::where('id',$data['plan_id'])->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
    }


    /**
     * 审核批量通过
     */
    public function planCollectResumes(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['plan_id']){$this->error('领用单不存在');}
        if(!$data['authorize']){$this->error('权限错误');}
        $idArr = explode(',',$data['plan_id']);
        //开启事务
        Db::startTrans();
        try{
            // if($data['authorize'] == 8){
            //     $planInfo['plan_status'] = 2;
            // }else
            if ($data['authorize'] == 2){
                $planInfo['plan_status'] = 4;
            }elseif ($data['authorize'] == 4){
                $planInfo['status'] = 1;
            }
            $resut = ControlClaimModel::whereIn('id',$idArr)->update($planInfo);
           // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 子表数据修改
            $applyPlan = Db::name('sn_control_claim_list')->whereIn('plan_id',$idArr)->update(['status'=>1]);
            if (!is_int($applyPlan)) {throw new \Exception("服务器错误");}
            //流程表数据修改
            $planTime = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            $applyList = Db::name('sn_control_claim_time')->where('admin_id',$data['admin_id'])->whereIn('collect_id',$idArr)->update($planTime);
            if (!$applyList) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
    }


    /**
     * 审核拒绝
     */
    public function planCollectRefusal()
    {
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['username']){$this->error('请先登陆');}
        if(!$data['plan_id']){$this->error('计划不存在');}
        if(!$data['authorize']){$this->error('权限错误');}
        if(!$data['refusal_cause']){$this->error("请填写拒绝原因");}
        $dateTime = date('Y-m-d H:i:s',time());
        $planTime = array('status'=>-1,'time'=>$dateTime,'to_reason'=>$data['refusal_cause']);
        //开启事务
        Db::startTrans();
        try{
            $resut = Db::name('sn_control_claim_time')->where(['collect_id'=>$data['plan_id'],'admin_id'=>$data['admin_id']])->update($planTime);
            if (!is_int($resut)) {$this->error('服务器错误');}
            
            $resut = Db::name('sn_control_claim_list')->where(['plan_id'=>$data['plan_id']])->update(['status'=>-1]);
            if (!is_int($resut)) {$this->error('服务器错误');}
            //退还库存
            $claim = ControlClaimModel::where('id',$data['plan_id'])->find()->toArray();
            $list = ControlClaimListModel::where('plan_id',$claim['id'])->select()->toArray();
            foreach ($list as &$v){
                //库存数量添加
                if(!Db::name('sn_enter_storehouse_'.$claim['admin_id'])->where('material_code',$v['material_code'])->inc('material_num',$v['material_num'])->update()) throw new \Exception("服务器错误");
            }
            $saveRes = ControlClaimModel::where('id',$data['plan_id'])->update(['status' => '-1','reason_name'=>$data['username'],'reason_id'=>$data['admin_id'],'to_reason'=>$data['refusal_cause'],'reason_time'=>$dateTime]);
            if(!$saveRes) throw new \Exception("服务器错误");
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success("数据已更新");
    }

    /**
     * 日志列表
     */
    public function planCollectLogList()
    {
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['id']){$this->error('数据不存在');}
        $where = array('key'=>$data['id']);
        $info = Db::name('sn_control_claim_log')->where($where)->order('id desc')->select();
        $this->success("ok",$info,1);
    }


    /*
    * 数量/备注  日志添加
    */
    public function remarks(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['username']){$this->error('请先登陆');}
        if(!$data['index']){$this->error('数据不存在');}
        if(!$data['plan_id']){$this->error('计划不存在');}
        if(!$data['remarks']){$this->error("请填写备注");}
        if(!$data['numbers']){$this->error("请填写修改得数量");}
        $info = ControlClaimListModel::where('id',$data['index'])->find()->toArray();
        if($data['numbers']>=0 && $data['numbers'] != ''){
            if($info['material_num'] < $data['numbers']){
                $this->error('数量过大');
            }elseif($info['material_num'] == $data['numbers']){
                $this->error('无变化');
            }
            //开启事务
            Db::startTrans();
            try{
                //库存数量添加
                if(!StorehouseDataModel::where('material_code',$info['material_code'])->inc('material_num',$info['material_num']-$data['numbers'])->update()) throw new \Exception("服务器错误");

                $saveAll = array(
                    'material_num'=>$data['numbers'],
                    'material_xjprice'=>round($data['numbers'] * $info['material_price'],2),
                );
                $saveinfo = ControlClaimListModel::where('id',$data['index'])->update($saveAll);
                if($saveinfo === false){throw new \Exception("服务器错误");}
                //添加日志
                $insetAll = array(
                    'plan_id'=>$data['plan_id'],
                    'remarks'=>$data['remarks'],
                    'key'=>$data['index'],
                    'original_num'=>$info['material_num'],
                    'save_num'=>empty($data['numbers'])?$info['material_num']:$data['numbers'],
                    'admin_id'=>$data['admin_id'],
                    'admin_name'=>$data['username'],
                    'time'=>date('Y-m-d H:i:s',time())
                );
                $logId = Db::name('sn_control_claim_log')->insertGetId($insetAll);
                if(!$logId){throw new \Exception("服务器错误");}
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
            $this->success('数据更新成功');
        }
    }
    
    /**
     * 物资退还更新
     */
    public function giveBackNum()
    {
        $input = input('post.');
        if(!$input['admin_id']){$this->error('请先登陆');}
        if(!$input['username']){$this->error('请先登陆');}
        $ControlClaimList = new ControlClaimListModel();
        $info = $ControlClaimList->where('id',$input['id'])->find()->toArray();
        if(!$info){$this->error('数据不存在');}
        if($info['material_num'] < $input['num']){$this->error('填写数量不可大于原本数量');}
        //开启事务
        Db::startTrans();
        try{
            //库存数量添加
            if(!StorehouseDataModel::where('material_code',$info['material_code'])->where('admin_id',$info['admin_id'])->inc('material_num',$input['num'])->update()) throw new \Exception("服务器错误");
            $number = $info['material_num']-$input['num'];
            $saveArr = array(
                'material_num'=>$number,
                'material_xjprice'=>round($number * $info['material_price'],2),
            );
            $saveinfo = ControlClaimListModel::where('id',$input['id'])->update($saveArr);
            if($saveinfo === false){return json(['code'=>500,'msg'=>'服务器繁忙']);}
            $admin_user = session('user');
            //添加日志
            $insetAll = array(
                'plan_id'=>$info['plan_id'],
                'remarks'=>'物资退还',
                'key'=>$input['id'],
                'original_num'=>$number,
                'save_num'=>$input['num'],
                'admin_id'=>$input['admin_id'],
                'admin_name'=>$input['username'],
                'time'=>date('Y-m-d H:i:s',time())
            );
            $logId = Db::name('sn_control_claim_log')->insertGetId($insetAll);
            if(!$logId){return json(['code'=>500,'msg'=>'服务器繁忙']);}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }










}